var cloudwalkobj;
var width=1;
var height=1;
var CW_StrSeverIp = "120.25.161.56:7000";
var CW_appID = "user";
var CW_appSecret = "12345";
var groupId;
var RecongniseData = "";
var m_mapFaceIdToObjId;				//人脸Id->图片对象ID
var m_mapObjIdToFaceId; 			//图片对象ID->人脸Id
var imgobjId;

function createPlugin(targetE) {
	cloudwalkobj = document.createElement("object");
	cloudwalkobj.width = width;
	cloudwalkobj.height = height;
	cloudwalkobj.id = "CloudWalkSDKPlugin";
	
	var bDet=BrowserDetect.browser;
	if("Explorer"==bDet)
	{
		cloudwalkobj.classid = "CLSID:B1597418-A51E-4140-8698-EE865439755C";	//IE
	}
	else if("Firefox"==bDet)
	{
		cloudwalkobj.type = "application/x-cloudface-sdk3.0";		//Firefox
	}
	else if("Chrome"==bDet)
	{
		cloudwalkobj.type = "application/x-cloudface-sdk3.0";		//Chrome
	}
	else
		{
		cloudwalkobj.type = "application/x-cloudface-sdk3.0";
	}

	targetE.appendChild(cloudwalkobj);
	
	if(!cloudwalkobj.valid)
	{
		alert("插件未安装");
		return false;
	}
	
	m_mapFaceIdToObjId = new Map();
	m_mapObjIdToFaceId = new Map();

	registerCallBack(cloudwalkobj, "cwRegisterFaceCallBack", RegisterFaceCallBack);
	registerCallBack(cloudwalkobj, "cwQueryFaceCallBack", QueryFaceCallBack);
	
	
	var config = cloudwalkobj.cwGetConfig();
	PraseConfig(config);
	
	var nRet = CreateGroup();
	if(nRet != 0)
	{
		return false;
	}
	return true;
}

function getSourceObjIdByImgObjId(objId)
{
	switch(objId)
	{
		case "index1":
			return "img1sorce";
		case "index2":
			return "img2sorce";
		case "index3":
			return "img3sorce";
		case "index4":
			return "img4sorce";
		case "index5":
			return "img5sorce";
		default:
			return "";
	}
}
function showLoading1(){
    document.getElementById("over").style.display = "block";
    document.getElementById("layout").style.display = "block";
	document.getElementById("reco").innerHTML="人脸创建中...";
}
function showLoading2(){
    document.getElementById("over").style.display = "block";
    document.getElementById("layout").style.display = "block";
	document.getElementById("reco").innerHTML="人脸识别中...";
}
//添加对比人脸
function click_GetBase64ByLocalImg(obj)
{
	if(groupId.length == 0)
	{
		//没有组 在创建一次
		var nRet = CreateGroup();
		if(nRet != 0)
		{
			return;
		}
	}
	
	var imgPath=cloudwalkobj.cwSelectFile();
	if(imgPath.length == 0)
	{
		return;
	}
	
	var imgData=cloudwalkobj.cwGetBase64ByLocalFile(imgPath);
	if(imgData == "" || imgData == null)
	{
		alert("加载图片失败");
		return;
	}
	
	
	var oldfaceId = m_mapObjIdToFaceId.get(obj.id);
	if(oldfaceId != null)
	{
		var ret = cloudwalkobj.cwRemoveFaceToGroup(CW_StrSeverIp, CW_appID, CW_appSecret, groupId, oldfaceId); //删掉老图片
		if(ret != 0)
		{
			var msg = "";
			if(ret == CW_FACENOTEXIT)
			{
				msg = "移除旧人脸数据失败数据不存在";
			}
			else
			{
				msg = "移除旧人脸数据失败错误码:" + ret;
				alert(msg);
				return;
			}
		}
		m_mapObjIdToFaceId.remove(obj.id);
		
		var ObjIdName = m_mapFaceIdToObjId.get(oldfaceId);
		var sourceObjIdName = getSourceObjIdByImgObjId(ObjIdName);
		if(sourceObjIdName != null)
		{
			document.getElementById(sourceObjIdName).innerHTML = ""; //清除老的分数
			m_mapFaceIdToObjId.remove(oldfaceId);
		}
		
	}
	
	
	var myDate = new Date();
	var time = myDate.getTime(); 
	var faceId = time.toString();
	
	imgobjId = obj.id;
	showImg(obj, imgPath, imgData);
	
	showLoading1();
	var nRet = cloudwalkobj.cwRegisterFace(CW_StrSeverIp, CW_appID, CW_appSecret, imgData,
		groupId 
		);
	if(nRet != 0)
	{
		hideLoading();
	}
	
}

//添加识别人脸
function click_GetRecongniseFace()
{
	var imgPath=cloudwalkobj.cwSelectFile();
	if(imgPath.length == 0)
	{
		return;
	}
	
	document.getElementById("fileText").value = "";
	document.getElementById("imghead").src = "../images/tianjiazhaopian.png";
	
	RecongniseData=cloudwalkobj.cwGetBase64ByLocalFile(imgPath);
	if(RecongniseData == "" || RecongniseData == null)
	{
		alert("加载图片失败");
		return;
	}
	
	document.getElementById("fileText").value = imgPath;
	var imgObj = document.getElementById("imghead");
	showImg(imgObj, imgPath, RecongniseData);

}

//注册人脸回调
function RegisterFaceCallBack(jsonStr)
{
	
	var jsonObj = $.parseJSON(jsonStr);
	var faceId = jsonObj.faceId;
	if(jsonObj.result == 0)
	{
		var nRet = cloudwalkobj.cwAddFaceToGroup(CW_StrSeverIp, CW_appID, CW_appSecret,groupId,faceId);
		if(nRet != 0)
		{
			clearmap(faceId);
			var msg = "添加人脸到组失败！";
			document.getElementById(imgobjId).src = "../images/renlianshibiezhaopian.png";
			alert(msg);
		}
		else
		{
			m_mapFaceIdToObjId.put(faceId, imgobjId);
			m_mapObjIdToFaceId.put(imgobjId, faceId);
		}
	}
	else
	{
		var str = "";
		if(jsonObj.result == CW_couldntConnect){
		str += "网络异常！";
		}else if(jsonObj.result == EnumLocalNetErrorSerAddr){
		str += "无法解析人脸识别服务主机地址！";
		}else if(jsonObj.result == EnumLocalNetErrorConSer){
		str += "无法连接到人脸识别服务主机！";
		}else if(jsonObj.result == CW_TimeOut){
		str += "访问人脸识别服务主机超时！";
		}else if(jsonObj.result == CW_IMGQUALITY_NOT_GOOD){
		str += "识别失败照片质量太差";
		}else if(jsonObj.result == CW_NORIGHT){
		str += "没有权限";
		}else{
		str += "注册人脸失败！失败信息：";
		str += jsonObj.resultInfo;
		}
		document.getElementById(imgobjId).src = "../images/renlianshibiezhaopian.png";
		alert(str);
		
	}
	
	imgobjId = "";
	//EnableButton();
	hideLoading();
}

//组内识别回调
function QueryFaceCallBack(jsonStr)
{
	//EnableButton();
	hideLoading();
	
	var jsonObj = $.parseJSON(jsonStr);
	if(jsonObj != "null")
	{
		if(jsonObj.result == 0)
		{
			var faceObj = jsonObj.faces;
			for(var i = 0; i < faceObj.length; i++)
			{
				var faceId = faceObj[i].faceId;
				var source = faceObj[i].score;
				var ImgobjId = m_mapFaceIdToObjId.get(faceId);
				var SourceObjId = getSourceObjIdByImgObjId(ImgobjId);
				document.getElementById(SourceObjId).innerHTML = source;
			}
		}
		else
		{
			
			var str = "";
			if(jsonObj.result == CW_couldntConnect){
			str += "网络异常！";
			}else if(jsonObj.result == EnumLocalNetErrorSerAddr){
			str += "无法解析人脸识别服务主机地址！";
			}else if(jsonObj.result == EnumLocalNetErrorConSer){
			str += "无法连接到人脸识别服务主机！";
			}else if(jsonObj.result == CW_TimeOut){
			str += "访问人脸识别服务主机超时！";
			}else if(jsonObj.result == CW_IMGQUALITY_NOT_GOOD){
			str += "识别失败照片质量太差";
			}else if(jsonObj.result == CW_NORIGHT){
			str += "没有权限";
			}else{
			str += "人脸识别失败！失败信息：";
			str += jsonObj.resultInfo;
			}

			alert(str);
		}
	}
	
}

function CreateGroup()
{
	var myDate = new Date();
	var nCurrenTime = myDate.getTime();
	groupId	= nCurrenTime.toString();
	var nret = cloudwalkobj.cwCreateGroup(CW_StrSeverIp, CW_appID, CW_appSecret, groupId);
	if(nret != 0)
	{
		groupId = "";
		var msg = "";
		if(nret == CW_NORIGHT)
		{
			msg += "创建组失败没有权限";
		}
		else
		{
			msg = "创建组失败!";
		}
		alert(msg);
	}
	else
	{
		//创建组成功的提示框。-- jinfude
		//alert("创建组 ( groupId = " + groupId + " ) 成功!");
	}
	
	return nret;
}

//组内识别
function faceRecongnise()
{

	if(RecongniseData.length == 0)
	{
		alert("请添加待识别图片！");
		return;
	}
	
	var num = m_mapFaceIdToObjId.size();
	if(num == 0)
	{
		alert("请往组中添加至少一张图片！");
		return;
	}
	
	//DisableButton();
	showLoading2();
	var nRet = cloudwalkobj.cwQueryFaceFromGroup(CW_StrSeverIp, CW_appID, CW_appSecret,groupId,RecongniseData,num);
	if(nRet != 0)
	{
		//EnableButton();
		hideLoading();
	}
	
}

function openCramera()
{
	var nRet = cloudwalkobj.cwStartCamera(0,0);
	
	if(nRet != 0)
	{
		var msg = "打开摄像头失败错误码:"  + nRet;
		alert(msg);
	}
	
	return nRet
}

function closeCramera()
{
	cloudwalkobj.cwStopCamera();
}

function takePicture()
{
	var Tempimg = cloudwalkobj.cwTakePictures();
	if(Tempimg == null || Tempimg.length == 0)
	{
		alert("拍照失败！");
		return;
	}
	
	if(ImgObjName == "imghead")
	{
		RecongniseData = Tempimg;
	}
	
	document.getElementById("fileText").value = "";
	var faceimg = document.getElementById(ImgObjName);
	
	if(isIE6_8())
	{
		var saveDir = "C:/cloudwalk/"; 					//图片保存的所在目录
		var filename = new Date().getTime()+".jpg";		//图片名称，如果文件名已存在则直接覆盖
		//var filename = "bestFace.jpg";				//文件名固定时，使用img.src = path;不能及时更新，还是显示上一张
		var filepath = saveDir + filename;
		var nret = cloudwalkobj.cwBase64ToFile(Tempimg, saveDir, filename);		//Base64保存为本地图片
		faceimg.src = 'file:///'+filepath;			//在Firefox下面必须添加file:///前缀才可以正确显示图片，IE有无皆可
	}
	else
	{
		faceimg.src = "data:image/jpeg;base64,"+ Tempimg;
	}
}

function PraseConfig(strJson)
{
	var jsonObj = $.parseJSON(strJson);
	if(jsonObj != "null")
	{
	 CW_StrSeverIp = jsonObj["ip"];
	 CW_appID =  jsonObj["appID"];
	 CW_appSecret =  jsonObj["appSecret"];
	 var nret = cloudwalkobj.cwInit(jsonObj["License"]);
	 if(nret != 0)
	 {
		var msg = "初始化SDK失败错误码：" + nret;
		alert(msg);
		return;
	 }
	}
}

/*function EnableButton()
{
	
	//$(str).attr("disabled", false); //该属性在火狐下得不到兼容
	$("#recogniseBtn").css('background-color','#CE4241');
	$("#recogniseBtn").attr("onclick","faceRecongnise()");
	
	$("#shangchuan1").attr("onclick","click_GetRecongniseFace()");
	$("#xiangji1").attr("onclick","showBg('imghead')");
	
	$("#index1").css('background-color','#F8EDEC'); 
	$("#index1").attr("onclick","click_GetBase64ByLocalImg(this)");
	$("#index2").css('background-color','#F8EDEC'); 
	$("#index2").attr("onclick","click_GetBase64ByLocalImg(this)");
	$("#index3").css('background-color','#F8EDEC'); 
	$("#index3").attr("onclick","click_GetBase64ByLocalImg(this)");
	$("#index4").css('background-color','#F8EDEC'); 
	$("#index4").attr("onclick","click_GetBase64ByLocalImg(this)");
	$("#index5").css('background-color','#F8EDEC'); 
	$("#index5").attr("onclick","click_GetBase64ByLocalImg(this)");
	
}

function DisableButton()
{
		//$(str).attr("disabled", true);
	
		$("#recogniseBtn").css('background-color','#949193');
		$("#recogniseBtn").attr("onclick","");
	
		$("#shangchuan1").attr("onclick","");
		$("#xiangji1").attr("onclick","");
	
		$("#index1").css('background-color','#949193');
		$("#index1").attr("onclick","");
		$("#index2").css('background-color','#949193');
		$("#index2").attr("onclick","");
		$("#index3").css('background-color','#949193');
		$("#index3").attr("onclick","");
		$("#index4").css('background-color','#949193');
		$("#index4").attr("onclick","");
		$("#index5").css('background-color','#949193');
		$("#index5").attr("onclick","");
}*/


function registerCallBackEach()
{
	//兼容谷歌
	//谷歌浏览器移除插件会析构，添加会创建
	var bDet=BrowserDetect.browser;
	if("Chrome"==bDet)
	{
		registerCallBack(cloudwalkobj, "cwRegisterFaceCallBack", RegisterFaceCallBack);
		registerCallBack(cloudwalkobj, "cwQueryFaceCallBack", QueryFaceCallBack);
	}

}

function clearmap(faceId)
{
	//清理有关人脸IdMap
	var ImgObjId = m_mapFaceIdToObjId.get(faceId);
	if(ImgObjId != null)
	{
		m_mapFaceIdToObjId.remove(faceId);
		m_mapObjIdToFaceId.remove(ImgObjId);
	}
}
